package top.chukongxiang.monitorservice.config.conditation.os;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.system.OsInfo;
import cn.hutool.system.SystemUtil;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.core.type.AnnotatedTypeMetadata;

/**
 * @author 楚孔响
 * @version 1.0
 * @date 2023/10/19 12:07
 */
public class ConditionOnOS implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        MergedAnnotations annotations = metadata.getAnnotations();
        MergedAnnotation<ConditionalOnOS> conditionalOnOs = annotations.get(ConditionalOnOS.class);
        OsInfo osInfo = SystemUtil.getOsInfo();
        Os[] osValues = conditionalOnOs.getEnumArray("value", Os.class);
        if (!ArrayUtil.contains(osValues, Os.ANY)) {
            if (!ArrayUtil.contains(osValues, Os.Windows) && osInfo.isWindows()) {
                return false;
            }
            if (!ArrayUtil.contains(osValues, Os.Linux) && osInfo.isLinux()) {
                return false;
            }
            if (!ArrayUtil.contains(osValues, Os.Mac) && osInfo.isMac()) {
                return false;
            }
        }
        Arch[] archs = conditionalOnOs.getEnumArray("arch", Arch.class);
        if (!ArrayUtil.contains(archs, Arch.ANY)) {
            if (!ArrayUtil.contains(archs, Arch.x86) && StrUtil.startWithIgnoreCase(osInfo.getArch(), "x86")) {
                return false;
            }
            if (!ArrayUtil.contains(archs, Arch.ARM) && StrUtil.startWithIgnoreCase(osInfo.getArch(), "arm")) {
                return false;
            }
            if (!ArrayUtil.contains(archs, Arch.MIPS) && StrUtil.startWithIgnoreCase(osInfo.getArch(), "mips")) {
                return false;
            }
        }

        Bit[] bits = conditionalOnOs.getEnumArray("bit", Bit.class);
        if (!ArrayUtil.contains(bits, Bit.ANY)) {
            String javaBit = System.getProperty("sun.arch.data.model");
            if (!ArrayUtil.contains(bits, Bit._64) && "64".equalsIgnoreCase(javaBit)) {
                return false;
            }
            if (!ArrayUtil.contains(bits, Bit._32) && "32".equalsIgnoreCase(javaBit)) {
                return false;
            }
        }
        return true;
    }

}
